package com.example.zsf.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.zsf.R;
import com.example.zsf.activity.mobile.MobileDetailActivity;
import com.example.zsf.adapter.MobileGridAdapter;
import com.example.zsf.base.Presenter;
import com.example.zsf.base.Result;
import com.example.zsf.base.ZSFClearFocus;
import com.example.zsf.base.ZSFFragment;
import com.example.zsf.base.ZSFInputBaseActivity;
import com.example.zsf.model.MobileModel;
import com.example.zsf.presenter.MobilePresenter;
import com.example.zsf.utils.DebouncedOnItemClickListener;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class PCFragment extends ZSFFragment implements ZSFClearFocus {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    EditText searchView;

    private Unbinder unbinder;
    private MobileGridAdapter mobileGridAdapter;

    List<MobileModel.MobileListModel> completeData;


    public PCFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View createView = inflater.inflate(R.layout.fragment_mobile, container, false);
        unbinder = ButterKnife.bind(this, createView);
        View view = inflater.inflate(R.layout.header_mobile, null);
        view.setTag("header");
        initUI(view);
        return createView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!StringUtils.isEmpty(searchView.getText().toString())) {
            searchView.setText("");
        }
    }

    private void initUI(View view) {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        mobileGridAdapter = new MobileGridAdapter(getActivity(), R.layout.item_mobile, 1);
        mobileGridAdapter.setOnItemClickListener(new DebouncedOnItemClickListener(400) {
            @Override
            public void onDebouncedItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                MobileModel.MobileListModel item = (MobileModel.MobileListModel) adapter.getItem(position);
                boolean doNotNeedGrab = item.getGift_total_num() == null || item.getGift_total_num().equals("0");
                Intent intent = new Intent(getActivity(), MobileDetailActivity.class);
                intent.putExtra("id", item.getAds_id());
                intent.putExtra("image_url", item.getAds_img());
                intent.putExtra("need_grab", !doNotNeedGrab);
                intent.putExtra("time", item.getAds_time());
                startActivity(intent);
            }
        });
        mobileGridAdapter.addHeaderView(view);
        recyclerView.setAdapter(mobileGridAdapter);
        recyclerView.addItemDecoration(new SpaceDecoration());

        searchView = view.findViewById(R.id.searchView);
        searchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() == 0) {
                    //恢复
                    mobileGridAdapter.setList(completeData);
                    return;
                }
                Logger.d(editable.toString());
                List<MobileModel.MobileListModel> mobileListModels = filterData(completeData, editable.toString());
                mobileGridAdapter.setList(mobileListModels);
            }
        });
        searchView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    view.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                } else {
                    view.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                }
            }
        });
        searchView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    ZSFInputBaseActivity activity = (ZSFInputBaseActivity) getActivity();
                    if (activity != null) {
                        activity.hideKeyboard();
                    }
                }
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                requestMobileList();
            }
        });
    }

    private List<MobileModel.MobileListModel> filterData(List<MobileModel.MobileListModel> target, String findString) {
        if (target == null) {
            return null;
        }
        List<MobileModel.MobileListModel> res = new ArrayList<>();
        for (MobileModel.MobileListModel model : target) {
            if (model.getAds_name().contains(findString)) {
                res.add(model);
            }
        }
        return res;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    private void initData() {
        requestMobileList();
    }


    private void requestMobileList() {
        disposed(MobilePresenter.getList(1, new Presenter.PresenterListener<Result<MobileModel>>() {
            @Override
            public void onSuccess(Result<MobileModel> object) {
                if (object.code.equals("1")) {
                    completeData = object.data.getAds_data();
                    mobileGridAdapter.setList(object.data.getAds_data());
                    refreshLayout.finishRefresh();
                } else {
                    if (completeData == null) {
                        mobileGridAdapter.setEmptyView(R.layout.view_data_empty);
                    }
                    ToastUtils.showShort(object.msg);
                }
            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort(error);
                if (completeData == null) {
                    mobileGridAdapter.setEmptyView(R.layout.view_data_empty);
                }
            }
        }));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void clearFocus() {
        if (searchView != null) {
            searchView.clearFocus();
        }
    }

    private static class SpaceDecoration extends RecyclerView.ItemDecoration {
        public SpaceDecoration() {
            super();
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            if (parent.getChildAdapterPosition(view) == 0) {
                return;
            }

            int min = ConvertUtils.dp2px(4);
            int max = ConvertUtils.dp2px(8);

            int position = parent.getChildAdapterPosition(view);

            if (position % 2 == 0) {
                // right
                if (position == 2) {
                    outRect.set(min, max, max, min);
                } else {
                    outRect.set(min, min, max, min);
                }
            } else {
                if (position == 1) {
                    outRect.set(max, max, min, min);
                } else {
                    outRect.set(max, min, min, min);
                }
            }
        }
    }
}